from __future__ import with_statement

import cgi
from webob import Response
from webob.exc import HTTPMovedPermanently, HTTPTemporaryRedirect
from fusion.http.controllers import BaseController
from fusion.db.profile import Profile
from fusion.db.exceptions import Unauthorized

class Person(BaseController):
    def index(self, req):
        view = self.load_view('person.html')

        if view:
            v = {}
            db = req.environ['fusion.db']

            v['hexlabel'] = req.urlvars['fusion.hexlabel']
            v['my_iid']  = db.get_my_iid()
            v['is_self']  = v['my_iid'] == v['hexlabel']
            v['is_empty'] = False

            # get raw profile obj
            profile = Profile()
            profile.read(db, v['hexlabel'])
            if not (profile.list_section_names() or profile.pic or profile.about):
                v['is_empty'] = True

            v['profile_fields'] = self._process_person_profile(db, profile)
            v['friend_list'] = self._process_friend_list(db, v['hexlabel'], v['my_iid'])
            v['group_list'] = self._process_group_list(db, v['hexlabel'], v['my_iid'])
            v['invitations'] = self._get_invitations(db)
            v['is_friend'] = v['friend_list']['items'].has_key(db.get_my_iid())

            # make it so
            return view.render(**v)
        else:
            return None


    def edit_picture(self, req):
        if req.method == 'POST':
            v = {}
            db = req.environ['fusion.db']

            v['hexlabel'] = req.urlvars['fusion.hexlabel']
            v['is_self']  = db.get_my_iid() == v['hexlabel']

            # get raw profile obj
            profile = Profile()
            profile.read(db, v['hexlabel'])


            if req.POST.has_key('do'):
                if req.POST['do'] == 'delete':
                    # delete picture
                    profile.pic = None

            if req.POST.has_key('generic#0#picture'):
                # save new picture
                upload = req.POST['generic#0#picture']
                if upload.__class__ == cgi.FieldStorage:
                    with upload.file as f:
                        newpic = f.read()

                    profile.pic = newpic

            # write profile
            try:
                profile.write(db, v['hexlabel'])
            except (Unauthorized, LookupError):
                #[FIXME: should something happen here?]
                pass

            # redirect to profile
            redir_url = '/person/'
            return HTTPMovedPermanently(location=redir_url)

        else:
            # GET
            view = self.load_view('person.edit_picture.html')

            if view:
                v = {}
                db = req.environ['fusion.db']

                v['hexlabel'] = req.urlvars['fusion.hexlabel']
                v['is_self']  = db.get_my_iid() == v['hexlabel']

                # get raw profile obj
                profile = Profile()
                profile.read(db, v['hexlabel'])
                v['profile'] = profile
                
                v['profile_fields'] = self._process_person_profile(db, profile)

                # engage -->
                return view.render(**v)
            else:
                return None


    def edit(self, req):
        if req.method == 'POST':
            v = {}
            db = req.environ['fusion.db']

            v['hexlabel'] = req.urlvars['fusion.hexlabel']
            v['is_self']  = db.get_my_iid() == v['hexlabel']

            # get raw profile obj
            profile = Profile()
            profile.read(db, v['hexlabel'])

            # get the public flags
            public_selectors = set([(key,val) for key,val in req.POST.items() if key.startswith('_public')])

            # get the generic fields
            generic_fields = set([(key,val) for key,val in req.POST.items() if key.startswith('generic')])

            # get the other profile fields
            profile_fields = set(req.POST.items()) - generic_fields - public_selectors

            #[TODO: convert to dictionaries no good?]
            public_selectors = dict(public_selectors)
            generic_fields = dict(generic_fields)
            profile_fields = dict(profile_fields)

            # clear existing fields (doesn't affect picture)
            profile.clear_all_fields()

            # update name
            name = (generic_fields['generic#0#name'] or '').strip()
            if name:
                profile.name = name

            # update about
            if public_selectors.has_key('_public_generic#0#about'):
                profile.set_about(generic_fields['generic#0#about'] or '', public=True)
            else:
                profile.set_about(generic_fields['generic#0#about'] or '', public=False)

            # write other fields
            for key,val in profile_fields.items():
                try:
                    section, n, field = key.split('#')
                    is_public = public_selectors.has_key('_public_%s' % key)

                    # special case for gender
                    if (section == 'personal' and field == 'gender'):
                        if not (val in ('Male', 'Female')):
                            val = ''

                    if (val):
                        profile.add_field(section, field, val, public=is_public)
                    else:
                        pass

                except:
                    pass

            # write profile
            try:
                profile.write(db, v['hexlabel'])
            except (Unauthorized, LookupError):
                #[FIXME: should something happen here?]
                pass

            # redirect to profile
            redir_url = '/person/'
            return HTTPMovedPermanently(location=redir_url)

        else:
            # GET
            view = self.load_view('person.edit.html')

            if view:
                v = {}
                db = req.environ['fusion.db']

                v['hexlabel'] = req.urlvars['fusion.hexlabel']
                v['is_self']  = db.get_my_iid() == v['hexlabel']

                # get raw profile obj
                profile = Profile()
                profile.read(db, v['hexlabel'])
                v['profile'] = profile
                
                v['profile_fields'] = self._process_person_profile(db, profile)

                # engage -->
                return view.render(**v)
            else:
                return None

